<template>
  <div>
    <el-form>
      <el-form-item>
        <el-input
            style="width:350px"
            v-model="state"
            placeholder="请输入名称"
            @keyup.enter="handleSearch"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="请选择" style="width: 100px">
              <el-option label="用户名" value="username" />
              <el-option label="真实姓名" value="realName" />
              <el-option label="邮箱" value="email" />
              <el-option label="电话" value="phone" />
              <el-option label="工号" value="stuId" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="handleSearch" @keyup.enter="handleSearch"/>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-button type="primary" plain @click="handleAdd">
      <el-icon><Plus /></el-icon>
      新增
    </el-button>
    <el-button type="danger" plain @click="handleDelete" :disabled="multipleSelection.length == 0">
      <el-icon><Delete /></el-icon>
      批量删除
    </el-button>
<!--    <el-button type="success" class="ml-5" @click="handleUpload">导入<el-icon class="ml-5"><Upload /></el-icon></el-button>-->
<!--    <el-button type="success" class="ml-5" @click="handleDownload">导出<el-icon class="ml-5"><Download /></el-icon></el-button>-->
  </div>

  <el-scrollbar>
    <el-table :data="tableData" fit
              v-loading="loading"
              table-layout="auto"
              style="width: 100%; margin-top: 15px;"
              :header-cell-style="{ background:'#eee','text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userName" label="用户名"  />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="email" label="邮箱"  />
      <el-table-column prop="telephone" label="电话"  />
      <el-table-column prop="stuId" label="工号" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" plain size="small" text @click="handleEdit(scope.row.userId)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" plain size="small" text @click="handleDelete(scope.row.userId)" >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getPageList"
          @current-change="getPageList"
      />
    </div>
  </el-scrollbar>

  <el-dialog
      v-model="centerDialogVisible"
      :title="dialogTitle"
      width="35%"
      @close="onCloseDialog"
      @open="onOpenDialog"
  >


    <el-form :model="userInfo" ref="userForm"  label-position="right" label-width="100px" :rules="rules" >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="userName" label="用户名">
            <el-input v-model="userInfo.userName" :disabled="editUserName" placeholder="请输入用户名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="realName" label="真实姓名">
            <el-input v-model="userInfo.realName" placeholder="请输入真实姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!userInfo.userId">
          <el-form-item prop="password" label="密码">
            <el-input v-model="userInfo.password" placeholder="请输入密码" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="userInfo.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="telephone" label="手机电话">
            <el-input v-model="userInfo.telephone" placeholder="请输入手机电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="stuId" label="工号">
            <el-input v-model="userInfo.stuId" placeholder="请输入工号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="role" label="角色">
            <el-select v-model="userInfo.roleIds"  multiple placeholder="请分配角色">
            <el-option
                v-for="item in roleSelectOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button type="info" @click="onCancel" style="margin-right: 10%">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {defineEmits, onMounted, reactive, ref} from "vue";
import {
  getPage,
  addUser,
  deleteUsers,
  updateUser,
  getUser,
  updateUserAndRoles,
  addUserAndRoles
} from "../../../api/userInfo.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Search, Edit, Plus, Minus, Remove} from "@element-plus/icons-vue";
import {getRoleSelect} from "@/api/role.js";

const emit = defineEmits(['hidden','show']) //未用到，加上解决警告，问题在哪不知道
  const tableData = ref([])
  const currentPage = ref(1)
  const pageSize = ref(15)
  const total = ref(0)
  const small = ref(false)
  const background = ref(false)
  const disabled = ref(false)
  const state = ref('')
  const select = ref('username')
  const centerDialogVisible = ref(false)
  const loading = ref(true)
  const roleSelectOptions = ref([])
  const multipleSelection = ref([])
  const editUserName = ref(false)
  const userForm = ref(null);
  const dialogTitle = ref('新增用户')
  const userInfo = reactive(defaultValue())
  function defaultValue(){
    return {
      userId: null,
      userName: null,
      password: null,
      realName: null,
      email: null,
      telephone: null,
      stuId: null,
      roleIds: [],
    }
  }

const rules = reactive({
  userName: [
    // required是否必填,message不符合此规则时的提示信息,
    // trigger触发此条规则校验的时机，有两个值, blur 或 change,默认就是blur和change都会进行校验
    // min此字段的最小长度，max此字段的最大长度
    // pattern 正则表达式
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9]{4,20}$/, message: '用户名长度为4 - 20位,只能由数字或字母构成'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确的邮箱'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  realName: [
    {required: true, message: '真实姓名不能为空', trigger: 'blur'},
  ],
  telephone: [
    {required: true, message: '电话不能为空', trigger: 'blur'},
  ],
  stuId: [
    {required: true, message: '工号不能为空', trigger: 'blur'},
  ],
})
  function reset(){
    Object.assign(userInfo,defaultValue())
  }
  onMounted(()=>{
    getPageList()
  })
  function handleSearch(){
    loading.value = true;
    getPage(currentPage.value,pageSize.value,select.value,state.value).then(res=>{
      if(res.code == 200){
        tableData.value = res.data.records
        total.value = res.data.total
      }else{
        ElMessage(res.msg);
      }
    }).finally(()=>{
      loading.value = false
    })
    state.value = ""
  }

  function handleAdd(){
    reset()
    dialogTitle.value = '新增用户'
    editUserName.value = false
    centerDialogVisible.value = true
  }

  function getPageList(){
    loading.value = true
    getPage(currentPage.value,pageSize.value).then(res=>{
      if(res.code == 200){
        tableData.value = res.data.records
        total.value = res.data.total
      }else{
        ElMessage(res.msg);
      }
    }).finally(()=>{
      loading.value = false
    })
  }
  async function handleEdit(userId){
    centerDialogVisible.value = false
    rules.password[0].required = false
    editUserName.value = true
    dialogTitle.value = '修改用户信息'
    await getUser(userId).then(res =>{
      userInfo.userId = res.data.userId
      userInfo.userName = res.data.userName
      userInfo.realName = res.data.realName
      userInfo.telephone = res.data.telephone
      userInfo.email = res.data.email
      userInfo.stuId = res.data.stuId
      userInfo.roleIds = []
      res.data.roles.forEach(item => userInfo.roleIds.push(item.roleId))
    })
    centerDialogVisible.value = true
  }
  function onCancel(){
    rules.password[0].required = true
    editUserName.value = false
    centerDialogVisible.value = false
  }
  function onCloseDialog(){
    rules.password[0].required = true
    editUserName.value = false
    centerDialogVisible.value = false
  }
  function onOpenDialog(){
    getRoleSelect().then(res =>{
      roleSelectOptions.value = res.data
    })
  }
  function onSubmit(){
    userForm.value.validate(valid => {
      if (valid) {
        if (userInfo.userId != null) {
          updateUserAndRoles(userInfo).then(res => {
            if(res.code == 200){
              centerDialogVisible.value = false
              ElMessage.success(res.msg)
              getPageList()
            }else{
              ElMessage.error(res.msg)
            }
          })
        } else {
          addUserAndRoles(userInfo).then(res => {
            if(res.code == 200){
              centerDialogVisible.value = false
              reset()
              ElMessage.success(res.msg)
              getPageList()
            }else{
              ElMessage.error(res.msg)
            }
          })
        }
      }
    })
    /**/
  }
  function handleSelectionChange(val){
    multipleSelection.value = val
  }
  function handleDelete(id){
    let ids = multipleSelection.value.length != 0 ? multipleSelection.value.map(item => item.userId) : id;
    ElMessageBox.confirm(
        '是否确认删除？',
        '系统提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(() => {
      deleteUsers(ids).then(res => {
        if(res.code == 200){
          ElMessage.success(res.msg)
        }
      }).finally(() =>{
        getPageList()
      })
    }).catch(() =>{
      ElMessage.info("取消删除")
    })
  }
</script>

<style scoped>
.pagination{
  padding: 20px 0;
  margin-left:55%;
  transform: translate(-50%,0);
}
</style>
